package com.chinasoft.rentalservice.controller;

import com.chinasoft.ms.dto.RentalDTO;
import com.chinasoft.ms.dto.RentalRecordDTO;
import com.chinasoft.ms.pojo.PageItem;
import com.chinasoft.ms.pojo.Rental;
import com.chinasoft.ms.pojo.Result;
import com.chinasoft.rentalservice.service.RentalService;
import com.chinasoft.rentalservice.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/RentalRecord")
public class RentalController {

    @Autowired
    private RentalService rentalService;

    @GetMapping
    public Result<PageItem<RentalRecordDTO>> getRentalPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Long rentalId,
            @RequestParam(required = false) Long carId,
            @RequestParam(required = false) Long userId,
            HttpServletRequest request) {
        // 从token中获取当前用户ID（假设你使用JWT）
        String token = request.getHeader("authorization");
        Long userId2 = Long.valueOf(JwtUtils.getAudience(token));


        RentalRecordDTO query = new RentalRecordDTO();
        // 如果是普通用户，只查询自己的数据
        if (query.getUserId() == null) {
            query.setUserId(userId2);
        }
        query.setRentalId(rentalId);
        query.setCarId(carId);
        query.setUserId(userId);
        PageItem<RentalRecordDTO> page = rentalService.queryByPageCond(pageNum, pageSize, query);
        return new Result<>(200, "查询成功", page);
    }

    @PostMapping
    public Result addRental(@RequestBody RentalRecordDTO rentalDTO) {
        boolean success = rentalService.addRental(rentalDTO);
        return success ? new Result<>(200, "添加成功") : new Result<>(500, "添加失败");
    }

    @PutMapping
    public Result updateRental(@RequestBody RentalRecordDTO rentalDTO) {
        boolean success = rentalService.updateRental(rentalDTO);
        return success ? new Result<>(200, "更新成功") : new Result<>(500, "更新失败");
    }

    @DeleteMapping("/deleteRecord/{id}")
    public Result deleteRental(@PathVariable Long id) {
        boolean success = rentalService.deleteRental(id);
        return success ? new Result<>(200, "删除成功") : new Result<>(500, "删除失败");
    }

    @PostMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<Long> ids) {
        boolean success = rentalService.deleteBatch(ids);
        return success ? new Result<>(200, "批量删除成功") : new Result<>(500, "批量删除失败");
    }

    @GetMapping("/carId/{carId}")
    public Result<RentalRecordDTO> getRentalByCarId(@PathVariable Long carId) {
        RentalRecordDTO rentalDTO = rentalService.getRentalByCarId(carId);
        return rentalDTO != null ? new Result<>(200, "查询成功", rentalDTO) : new Result<>(404, "未找到租赁记录");
    }



}
